﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace UtilsBase
{
    public static class UtilsAppsetting
    {
        static IConfigurationBuilder builder;
        static string path = UtilsFileHelper.getParnetDirectory();
        static IConfigurationRoot configuration;
        public static string GetSettings(string key)
        {
            if (builder == null)
            {
                builder = new ConfigurationBuilder()
          .SetBasePath(Directory.GetCurrentDirectory())
          .AddJsonFile(path + "/Configs/appsettings.json", optional: false, reloadOnChange: true);
                configuration = builder.Build();
            }
            //Console.WriteLine("getKey: " + key);
            return configuration[key];
        }

        public static void WriteSettings(string root, string key, string strValue)
        {

            // 读取appsettings.json文本内容
            string fileName = "";
            if (UtilsMachineInfo.getRumEnvironment() == "development")
            {
                //开发环境
                fileName = "appsettings.json";
            }
            else if (UtilsMachineInfo.getRumEnvironment() == "test")
            {
                //开发环境
                fileName = "appsettings_test.json";
            }
            else if (UtilsMachineInfo.getRumEnvironment() == "product")
            {
                //开发环境
                fileName = "appsettings_product.json";
            }
            else
            {
                fileName = "appsettings_" + UtilsMachineInfo.getRumEnvironment() + ".json";
            }

            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Configs/", fileName);
            string text = File.ReadAllText(filePath);
            // 修改配置项
            JObject obj = JObject.Parse(text);
            obj[root][key] = strValue;
            // 重新写入appsettings.json
            string result = obj.ToString();
            File.WriteAllText(filePath, result);
        }

    }

}
